import React from 'react';
import { List, Tools, InputItem, PickerView, Checkbox, Radio,Select, Button } from 'weaver-mobile';
import { observer, inject} from 'mobx-react';
import { withRouter } from 'react-router-dom';

const getLabel = Tools.getLabel;
const CheckboxItem = Checkbox.CheckboxItem;
const RadioItem = Radio.RadioItem;

const selectType = [
  // key代表类型与PC端保持一致
  {label: getLabel(387374,'按天'),value: getLabel(387374,'按天'),keys: 'day',key: '3'},
  {label: getLabel(387375,'按周'),value: getLabel(387375,'按周'),keys: 'week',key: '0'},
  {label: getLabel(387376,'按月'),value: getLabel(387376,'按月'),keys: 'month',key: '1'},
  {label: getLabel(387377,'按年'),value: getLabel(387377,'按年'),keys: 'year',key: '2'},
];

const perWeek = [
  {label: getLabel(16100,'周一'),value: 1,key: 1 },
  {label: getLabel(16101,'周二'),value: 2,key: 2 },
  {label: getLabel(16102,'周三'),value: 3,key: 3 },
  {label: getLabel(16103,'周四'),value: 4,key: 4  },
  {label: getLabel(16104,'周五'),value: 5,key: 5  },
  {label: getLabel(16105,'周六'),value: 6,key: 6  },
  {label: getLabel(16106,'周日'),value: 7,key: 7  },
];

const weeks = [
  {label: getLabel('389717','第一个') ,value: 1,key: 0},
  {label: getLabel('389988','第二个') ,value: 2,key: 1},
  {label: getLabel('389719','第三个') ,value: 3,key: 2},
  {label: getLabel('389720','第四个') ,value: 4,key: 3},
  {label: getLabel('389721','第五个') ,value: 5,key: 4},
  {label: getLabel('389722','最后一个') ,value: -1,key: 5},
];

@inject('createStore')
@observer
@withRouter

export default class RepeatType extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      type:'day',
      repeatType: false, // 重复类型
      repeatRate: false, // 重复频率
      month_firstOrLast: '0', // 正数:0/倒数:1
      year_firstOrLast: '0', // 正数:0/倒数:1
      selectRepeatType: getLabel(387374,'按天'),
      selectRepeatTypeNum: '',
      dateRange: getLabel(383378,'天'),
      count: '', // 频率（每几*）
      value: 1, //单选按钮（日期--星期）
      val: [1,1], // 初始化--第几个星期几
      checked: false, // 按年-星期
      repeatMessage: [], 
      monthMessage: [], // 月份信息
      dateMessage: [], //日期信息
      weekMessage: [], // 周信息
    }

  }
  
  componentDidMount() {
      // 编辑
      const { repeatInfo } = this.props.createStore;
      const { timeModul,interval,fer_2,fer_1,fer_0,fer_3,monthType,yearType,switchWeek } = repeatInfo;
      let arr = []
      arr.push(parseInt(fer_3[0],10),parseInt(fer_3[1],10))
      let repeatTypeString = '';
      selectType.forEach(item => {
        if(item.key === timeModul) {
          repeatTypeString = item.label;
        }
      });
      this.setRepeatType(timeModul);
      this.setState({
        selectRepeatType: repeatTypeString,
        count: interval,
        weekMessage: fer_0,
        dateMessage: fer_1,
        monthMessage: fer_2,
        val: arr,
        month_firstOrLast: monthType,
        year_firstOrLast: yearType,
        value: parseInt(switchWeek,10),
      })
      // this.setTypeVisible(timeModul);
  }

  componentWillUnmount() {

  }

  setRepeatType = (timeModul) => {
    switch(timeModul) {
      case '0' : this.setState({dateRange: getLabel(383377,'周'), selectRepeatTypeNum: '0', type: 'week'}); break;
      case '1' : this.setState({dateRange: getLabel(33452,'月'), selectRepeatTypeNum: '1', type: 'month'}); break;
      case '2' : this.setState({dateRange: getLabel(383372,'年'), selectRepeatTypeNum: '2', type: 'year'}); break;
      case '3' : this.setState({dateRange: getLabel(383378,'天'), selectRepeatTypeNum: '3', type: 'day'}); break;
      default: ;
    }
  }

  onScrollChangeRepeatType = (e) => {
    this.setState({selectRepeatType: e[0]})
    const { dateRange } = this.state;
    selectType.forEach((item) => {
      if(item.value === e[0]) {
        this.setRepeatType(item.key);
      }
    });
 
    if(dateRange === getLabel(383378,'天')) {
      this.setState({
        dateMessage: [],
        monthMessage: [],
        repeatMessage: [],
        weekMessage: []
      });
    }else if(dateRange === getLabel(383377,'周')) {
      this.setState({
        count: '',
        dateMessage: [],
        monthMessage: [],
        repeatMessage: [],
      });
    }else if(dateRange === getLabel(33452,'月')) {
      this.setState({
        count: '',
        dateMessage: [],
        monthMessage: [],
        repeatMessage: [],
        weekMessage: []
      });
    }else if(dateRange === getLabel(383372,'年')) {
      this.setState({
        count: '',
        dateMessage: [],
        monthMessage: [],
        repeatMessage: [],
        weekMessage: []
      });
    }
  }

  onChangeRepeatCount = (e) => {
    // setRepeatInfo({interval: e[0]});
    e[0] === 1 && this.setState({count: ''})
    e[0] !== 1 && this.setState({count: e[0]})
  }
  
  setTypeVisible = () => {
    // 重复类型
    let { repeatType } = this.state;
    this.setState({repeatType: !repeatType, repeatRate: false});
  }

  setRateVisible = () => {
    let { repeatRate,  } = this.state;
    this.setState({repeatRate: !repeatRate,repeatType: false});
  }

  messageString = () => {
    const { count, dateRange, monthMessage, dateMessage, weekMessage,type,value,val,month_firstOrLast,year_firstOrLast } = this.state;
    let message = '';
    let frequencyLabel = '';
    let echoLabel = '';
    let monthstring = [];
    let weekstring = [];
    let datestring = [];
    let week_perWeek = [];
    let firstOrLast = type === 'month' ? month_firstOrLast : type === 'year' ? year_firstOrLast : '';
    if(dateRange === getLabel(383378,'天') || dateRange === getLabel(383377,'周')) {
      frequencyLabel = getLabel('21977','每') ;
      echoLabel = getLabel('391138','重复一次') ; 
    }else{
      frequencyLabel = getLabel('391139','于每') ;
      echoLabel =  getLabel(18082,'重复');
    } 
    perWeek.map(item => {
      if(weekMessage.indexOf(item.value+"") !== -1) {
        weekstring.push(item.label);
      }
      return '';
    });
    dateMessage.map(item => {
      datestring.push(getLabel(15323,'第')+item+getLabel(385820,'日'));
      return '';
    });
    monthMessage.map(item => {
      monthstring.push(item+getLabel(33452,'月'));
      return '';
    });
    week_perWeek = this.weeks_perWeek(val);
    message = frequencyLabel + (count === 1 ? '' : count) + dateRange + 
              (type === 'week' ? weekstring : '') + 
              // (type === 'month' ? (month_firstOrLast === '0' ? '正数' : '倒数'): '')+
              // (type === 'year' ? (year_firstOrLast === '0' ? '正数' : '倒数'): '')+
              ((type === 'month' || type === 'year' )&&value===0 ? (firstOrLast === '0' ? getLabel(18817,'正数') : getLabel(18816,'倒数')) : '') +
              (type === 'year' ? monthstring : '') + 
              // ((type === 'year' && monthstring.length>0) ? getLabel(33800,'的') : '') +
              ((type === 'month' || type === 'year') && value === 1  ? getLabel(33800,'的') : '')+
              ((type === 'month' || type === 'year') && value === 0 ? datestring : '') + 
              ((type === 'month' || type === 'year') && value === 1  ? week_perWeek : '') +
              echoLabel;
    return message;
  }

  repeatTypeChange = () => {
    let { dateRange } = this.state;
    const perDay = () => {
      let arr = [];
      let array = [];
      for(let i = 1; i <= 99; i++) {
        let obj = {};
        obj = i ;
        arr.push({label: obj,value: obj});
      }
      array.push(arr)
      arr = [
        {label: dateRange,value: dateRange }
      ];
      array.push(arr);
      return array;
    }

    return perDay();
  }

  onChangeRadio = (value) => {
    if(value === 0) {
      this.setState({ value: value, firstOrLast: '0', dateMessage: [], repeatMessage: [], val: [1,1]})
    }
    if(value === 1) {
      this.setState({ value: value, dateMessage: [], repeatMessage: [] })
    }
  }

  onclickActive = (e) => {
    const {  dateRange, } = this.state;
    let checked = [];
    let selected = [];
    let innerText = e.target.innerText;
    let check = [];
    let str = e.target.className;
    let ee = e.target.classList;
    if(str.indexOf('active') === -1) {
      ee.add('active');
      selected.push(innerText);
    }else{
      ee.remove('active')
    } 
    let childObj = e.target.parentElement.childNodes;
    for(let i=0; i<childObj.length; i++) {
      let classname = childObj[i].className;
      if(classname.indexOf('active') !== -1) {
        let temp = dateRange === getLabel(33452,'月') ? childObj[i].textContent : childObj[i].textContent.split(getLabel(33452,'月'))[0];
        check.push(temp);
        checked.push(temp)
      }
    }
    const dateFunction = () => {
      // setRepeatInfo({fer_1: check});
      this.setState({dateMessage: checked}); // 日期
    }
    if(dateRange === getLabel(33452,'月')) {
      dateFunction();
    }
    if(dateRange === getLabel(383372,'年')) {
      if(str.indexOf('month-grid')>-1) {// 日期
        dateFunction();
      }
      if(str.indexOf('year-grid')>-1) {// 月份
        // setRepeatInfo({fer_2: check});
        this.setState({monthMessage: checked});
      }
    }
  }

  weeks_perWeek = (arr) => {
    // 第几个星期几
    let repeatTime = [];
    weeks.forEach((item) => {
      if(item.value === arr[0]) {
        repeatTime.push(item.label);
      }
    })
    perWeek.forEach((item) => {
      if(item.value === arr[1]) {
        repeatTime.push(item.label);
      }
    })
    return repeatTime;
  }

  selectWeeks = (e) => {
    let repeatTime = this.weeks_perWeek(e);
    this.setState({val: e, repeatMessage: repeatTime});
  }

  getSelectWeek = (check) => {
    this.setState({checked: check}) 
  }

  getChecked = (e, value) => {
    const { setRepeatInfo } = this.props.createStore;
    const { weekMessage } = this.state;
    let arr = weekMessage;
    if(e) {
      arr.push(value.toString());
    }else{
      arr.splice(arr.indexOf(value.toString()),1);
    }

    this.setState({weekMessage: arr});
    setRepeatInfo({fer_0: arr});
  }

  // 按星期
  getWeeks = () => {
    let fields = [];
    const { weekMessage } = this.state;
    perWeek.map(i => (
      fields.push(
        <CheckboxItem defaultChecked={weekMessage.indexOf(i.key+'') === -1 ? false : true} key={i.value} onChange={(e) => {this.getChecked(e.target.checked, i.value)}}>
          {i.label}
        </CheckboxItem>
      )
    ))
    return fields;
  }

  // 第几个-星期几
  getWhichWeeks = () => {
    const { val } = this.state;
    let fields = (
      <div className='repeat-weeks-list' key={'getwichweeks'}>
        { // 第几个--星期几
          <PickerView
            cols={2}
            value={val}
            data={[weeks,perWeek]}
            cascade={false}
            onScrollChange={(e) => { this.selectWeeks(e) }}
          />
        }
      </div>
    );

    return fields;
  }
  // 按月
  getMonths = () => {
    const perMonth = [
      { value: 0, label: getLabel(382823,'日期') },
      { value: 1, label: getLabel(389991,'星期') },
    ];
    let {value,type,dateMessage,month_firstOrLast,year_firstOrLast} = this.state;
    let fields = [];
    let field = [];
    let W = document.body.clientWidth;
    perMonth.map(i => (
      fields.push(
        <RadioItem key={i.value} checked={value === i.value} onChange={() => this.onChangeRadio(i.value)}>
          {i.label}
        </RadioItem>
      )
    ))
 
    fields.push(
      // <List>
      // <PickerView
      //   cols={1}
      //   value={[value]}
      //   data={perMonth}
      //   onScrollChange={(e) => {this.onChangeRadio(e)}}
      // />
      // </List>
    );

    Array.from(new Array(31)).map((i,index) =>(
      field.push(
        <div className={dateMessage.indexOf((index+1).toString()) === -1 ? 'month-grid' : 'month-grid active'} 
          key={index} text={index+1} style={{width: (W - 7)/7}} onClick={(e) => {this.onclickActive(e)}}>
          {index+1}
        </div>
      )
    ));  
    if(value === 0) {
      const options = [
        { key: '0', showname: getLabel(18817,'正数')},
        { key: '1', showname: getLabel(18816,'倒数')},
      ]
      let firstOrLast = type === 'month' ? month_firstOrLast : type === 'year' ? year_firstOrLast : '';
      fields.push(
        <Select
          key={'select'}
          value={firstOrLast}
          label={getLabel(18817,'正数')+'/'+getLabel(18816,'倒数')}
          options={options}
          viewAttr={0}
          style={{marginLeft: -7}}
          onChange={(key, showname) => {
            // this.setState({firstOrLast: key});
            type === 'month' && this.setState({month_firstOrLast: key});
            type === 'year' && this.setState({year_firstOrLast: key});
          }}
        />
      );
      fields.push(<div className="month-list"  key={'month-list'}>{field}</div>)
    }
    if(value === 1) {
      fields.push(this.getWhichWeeks());
    }
    return fields;
  }

  // 按年
  getYears = () => {
    let W = document.body.clientWidth;
    const { checked, monthMessage } = this.state;
    let field = [];
    let fields = [];
    Array.from(new Array(12)).map((i, index) => (
      field.push(
        <div className={monthMessage.indexOf((index+1).toString()) === -1 ? "year-grid" : "year-grid active"} 
          key={index} style={{width: (W-4)/4}}  onClick={(e) => {this.onclickActive(e)}} >
          {index+1}{getLabel(33452,'月')}
        </div>
      )
    )); 

    fields.push((<div className="year-list" style={{}} key={'year-list'}>{field}</div>));
    fields.push(
      // <List.Item
      //   key='weekRadio'
      //   extra={<Switch
      //     checked={this.state.checked}
      //     onClick={(check) => { this.getSelectWeek(check) }}
      //   />}
      // >{getLabel(18518,'星期')}</List.Item>
    );

    checked && fields.push(this.getWhichWeeks());

    return fields;
  }

  doSubmit = () => {
    const {selectRepeatTypeNum,count,weekMessage,dateMessage,monthMessage,val,month_firstOrLast,year_firstOrLast,value} = this.state;
    const {setRepeatInfo} = this.props.createStore;
    setRepeatInfo({
      timeModul: selectRepeatTypeNum, 
      interval: count,
      fer_0: weekMessage,
      fer_1: dateMessage,
      fer_2: monthMessage,
      fer_3: val,
      monthType: month_firstOrLast,
      yearType: year_firstOrLast,
      switchWeek: value,
    });
    this.props.history.go(-1);
  }

  render() {
    const { count, dateRange, type, repeatRate,repeatType,selectRepeatType} = this.state;
    // let H = document.body.clientHeight;
    let H = window.innerHeight;
    return (
      <div>
        <div className="repeatTypeSelect" style={{height: H - 48,overflow: 'auto',WebkitOverflowScrolling: 'touch'}}>
          <List>
            <InputItem
              editable={false}
              moneyKeyboardAlign="right"
              value={selectRepeatType}
              onClick={() => { this.setTypeVisible() }}
            > {getLabel(391140,'重复类型')}</InputItem>
            {repeatType && <div className="repeat-picker-view-item">
                <PickerView
                  cols={1}
                  value={[selectRepeatType]}
                  data={selectType}
                  onScrollChange={(e) => { this.onScrollChangeRepeatType(e) }}
                />
              </div>
            }
            <InputItem
              editable={false}
              value={( count === 1 ? '' : count) + dateRange}
              onClick={() => { this.setRateVisible() }}
            >{getLabel('21977','每')}</InputItem>
            {repeatRate && <div className="repeat-picker-view-item" >
                <PickerView
                  cols={2}
                  value={[count]}
                  data={this.repeatTypeChange()}
                  cascade={false}
                  onScrollChange={(e) => { this.onChangeRepeatCount(e) }}
                />
              </div>
            }

            <div className="repeatMessage">
              <label>{getLabel(391141,'日程将')}{this.messageString()}</label>
            </div>
            {
              type === 'week' && <div className="repeat-week-list">
                {
                  this.getWeeks()
                }
              </div>
            }
            {
              type === 'month' && <div className="repeat-month-list">
                {
                  this.getMonths()
                }
              </div>
            }   
            {
              type === 'year' && <div className="repeat-year-list" >
                {
                  this.getYears()
                }
                {
                  this.getMonths()
                }
              </div>
            }
          </List>
        </div>
        <div className='repeatTypeSelect-button'>
          <Button type="primary" onClick={() => {this.doSubmit()}}>{getLabel(386788,'确定')}</Button>
        </div>
      </div>
    );
  }
}